<template>
	<view class="login">
		<navbar title="授权登录"></navbar>
		<view class="main" :style="{paddingTop: getNavbarHeight()  + 'px'}">
			<view class="header u-flex-col u-col-center">
				<image src="/static/images/logo.png" mode="aspectFill" class="logo"></image>
				<p class="title">欢迎登录美条街</p>
				<p class="text">为了更好的为您提供服务，请你先完成微信授权</p>
			</view>
			<view class="login-button">
				<button :open-type="buttonOpenType" @getphonenumber="wechatPhoneNumber"
					@click="isAgree ? '' : wechatPhoneNumber()" class="button">微信授权登录</button>
			</view>
			<view class="footer u-flex-center">
				<view class="select u-flex-center" @click="selectClick">
					<uv-icon name="checkmark" color="#000000" size="14" v-if="isAgree"></uv-icon>
				</view>
				<view class="footer-content">
					<span class="agree" @click="selectClick">阅读并同意</span>
					<span class="user-agree" @click="navigateTo('/subPackages/agreement/index?type=1')">《用户协议》</span>
					<span class="privacy-agree"
						@click="navigateTo('/subPackages/agreement/index?type=2')">《用户隐私条款》</span>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { ref } from 'vue';
	import { getNavbarHeight } from '@/utils/system.js';
	import { apiWxMiniMobileRegister } from '@/api/user.js';
	import { showToast, getPageEmit } from '@/utils/common.js';
	import { switchTab, navigateTo } from '@/utils/router.js'
	import eventBus from '@/utils/eventBus.js'
	import useUserStore from '@/store/modules/user.js'
	const isAgree = ref(false);
	const buttonOpenType = ref('');
	const userStore = useUserStore();

	// 获取上一个页面路径
	const getPreviousPagePath = () => {
		const pages = getCurrentPages();
		if (pages.length >= 2) {
			const prevPage = pages[pages.length - 2];
			return prevPage.route || prevPage.__route__; // 兼容不同版本的 uni-app
		}
		return '';
	};

	// 切换同意协议状态的函数
	const selectClick = () => {
		isAgree.value = !isAgree.value;
		buttonOpenType.value = isAgree.value ? 'getPhoneNumber' : ''
	};

	// 微信手机号授权函数
	const wechatPhoneNumber = async (e) => {
		// 检查是否同意协议
		if (!isAgree.value) {
			showToast('请阅读并同意协议');
			return;
		}
		// 检查用户是否拒绝授权
		if (e.detail.errMsg === 'getPhoneNumber:fail user deny') {
			showToast('您已拒绝手机号授权');
			return;
		}
		// 显示加载提示
		uni.showLoading({
			title: '获取授权中...'
		});
		try {
			// 进行微信登录获取 code
			const { code } = await new Promise((resolve, reject) => {
				uni.login({
					provider: 'weixin',
					success: (res) => resolve(res),
					fail: (err) => reject(err)
				});
			});
			// 构建请求参数
			const params = {
				tenantId: "000000",
				grantType: "xcx",
				clientId: "405a2030cd2846f28e3a7c8951222911",
				code,
				appid: uni.getAccountInfoSync().miniProgram.appId,
				encryptedData: e.detail.encryptedData,
				iv: e.detail.iv,
				parent_id: uni.getStorageSync('parent_id') || 0,
				institution_id: uni.getStorageSync('institution_id') || 0
			};
			// 调用接口进行手机号注册
			const { data } = await apiWxMiniMobileRegister(params);
			// 设置token
			userStore.setToken(data?.access_token)
			showToast('登录成功！');
			// 触发登录成功事件
			getPageEmit(getPreviousPagePath())
			eventBus.value.emit('getUserInfo');
			switchTab('/pages/index/index');
		} catch (error) {
			// 捕获并处理错误
			console.error('授权过程中出现错误:', error);
			showToast('授权失败，请稍后重试');
		} finally {
			// 无论成功或失败，都隐藏加载提示
			uni.hideLoading();
		}
	};
</script>

<style lang="scss" scoped>
	.login {
		padding-top: 160rpx;

		.header {

			.logo {
				width: 140rpx;
				height: 140rpx;
				display: block;
			}

			.title {
				line-height: 1rem;
				padding: 30rpx 0;
				font-family: Source Han Sans CN, Source Han Sans CN;
				font-weight: bolder;
				font-size: $font-size-36;
				color: $base-color;
			}

			.text {
				line-height: 1rem;
				font-family: Source Han Sans CN, Source Han Sans CN;
				font-weight: 400;
				font-size: $font-size-24;
				color: #686868;
			}
		}

		.login-button {
			padding-top: 190rpx;

			.button {
				width: 548rpx;
				height: 80rpx;
				background: $base-color;
				border-radius: 50rpx;
				font-family: Source Han Sans CN, Source Han Sans CN;
				font-weight: 400;
				font-size: $font-size-32;
				color: $base-color-white;
				line-height: 80rpx;
			}
		}

		.footer {
			padding-top: 30rpx;

			.select {
				width: 34rpx;
				height: 34rpx;
				border: 1rpx solid $base-color;
				border-radius: 50%;
			}

			.footer-content {
				padding-left: 20rpx;

				.agree {
					font-family: Source Han Sans CN, Source Han Sans CN;
					font-weight: 400;
					font-size: $font-size-24;
					color: $base-light-color;
				}

				.user-agree {
					padding: 0 6rpx;
					font-family: Source Han Sans CN, Source Han Sans CN;
					font-weight: 400;
					font-size: $font-size-24;
					color: #ED290A;
				}

				.privacy-agree {
					font-family: Source Han Sans CN, Source Han Sans CN;
					font-weight: 400;
					font-size: $font-size-24;
					color: #ED290A;
				}
			}
		}
	}
</style>